<template>
  <div>
    <p>
      {{title}}
      <span v-if="date>0"><span class="time">{{date}}</span>天</span>
      <span class="time">{{hourse}}</span>时
      <span class="time">{{minutes}}</span>分
      <span class="time">{{second}}</span>秒
    </p>
  </div>
</template>
<script>
export default {
  props: {
    // 结束时间
    endTime: {
      type: Number,
      default: 0
    },
    //开始时间
    startTime: {
      type: Number,
      default: 0
    },
    //当前时间
    nowTime: {
      type: Number,
      default: 0
    },
    timeTitle: {
      type: String,
      default: ""
    },
    type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      time: 0,
      hourse: "00", //时
      minutes: "00", //分
      second: "00", //秒
      date: 0,
      timer: null, //计时器
      title: this.timeTitle
    };
  },
  created() {
    if (this.nowTime < this.startTime) {
      this.title = "离活动开始还有";
      this.time = this.startTime - this.nowTime;
      this.countTime();
    } else if (this.nowTime < this.endTime) {
      if (this.title == "") {
        this.title = "离活动结束还剩";
      }
      this.time = this.endTime - this.nowTime;
      this.countTime();
    }
  },
  methods: {
    countTime() {
      //判断是否已结束
      if (this.time < 0) {
        this.$emit("time-over");
        return;
      }
      
      //格式化时间
      this.format(this.time);
      //递归每秒调用countTime方法，显示动态时间效果，延时器没有用定时器
      this.timer = setTimeout(() => {
        this.time--;
        this.countTime();
      }, 1000);
    },

    format(time) {
      //定义变量 h,m,s保存倒计时的时间
      var d, h, m, s;
      d = Math.floor( time / 60 / 60 / 24 );
      h = checkTime(Math.floor((time / 60 / 60) % 24));
      m = checkTime(Math.floor((time / 60) % 60));
      s = checkTime(Math.floor(time % 60));
      //将0-9的数字前面加上0
      function checkTime(i) {
        if (i < 10) {
          i = "0" + i;
        }
        return i;
      }
      //将倒计时赋值
      this.date = d;
      this.hourse = h;
      this.minutes = m;
      this.second = s;
    }
  }
};
</script>
<style scoped lang="scss">
p {
  font-size: 0.12rem;
  font-weight: 400;
  color: rgba(48, 49, 51, 1);
  line-height: 0.24rem;
  height: 0.24rem;
  .time {
    width: 0.24rem;
    height: 0.24rem;
    background: rgba(238, 238, 238, 1);
    border-radius: 0.02rem;
    font-size: 0.16rem;
    font-weight: 500;
    color: rgba(0, 136, 255, 1);
    margin: 0 0.04rem;
    padding: 2px 3px;
  }
}
</style>


